import logging

import io.ioloop

log = logging.getLogger('api')

#------------------------------------------------------------------------------
class API:
    """Defines the interface clients have to the cell phone daemon."""
    
    def __init__(self, master, addr):
        self.master = master
        self.client = None

        if addr == '-' or addr == 'stdin':
            log.info('using stdin for IPC')
            self.server_sock = None
            self.client = ApiSockHandle(self, io.ioloop.StdinSockAdapter())
            io.ioloop.master_loop.add_handle(self.client_)
        elif ':' in addr:
            a, p = addr.split(':')
            p = int(p)
            log.info('using TCP for IPC')
            self.server_sock = io.ioloop.ListenHandle((a,p), ConnectFactory(self))
            io.ioloop.master_loop.add_handle(self.server_sock)
        else:
            log.info('using UNIX domain for IPC')
            self.server_sock = io.ioloop.UnixListenHandle(addr, ConnectFactory(self))
            self.client_ = None
            io.ioloop.master_loop.add_handle(self.server_sock)            

    def send_client_sms(self):
        # XXX/bowei -----
        msgs = self.master.db.get_messages(True)
        for m in msgs:
            self.client.send_frame("s %s %s" % (m['number'], m['text']))
        log.debug('reading msgs %s' % msgs)
    
    def process_api_msg(self, msg):
        # XXX/bowei ----
        try:
            if msg == '':
                log.debug('api client disconnected')
                self.client.close()
            elif msg[0] == 's':
                _, modem, number, uniq, b64_bytes = l.split(' ', 4)
                self.master.send_sms(modem, number, uniq, b64_bytes)
        except ValueError, e:
            log.error('error in API command: "%s"' % l)

#----------------------------------------------------------------------------- 
class ConnectFactory(io.ioloop.ListenFactory):
    def __init__(self, api):
        self.api = api
        
    def make_handle(self, sock):
        log.info('API socket opened')
        a = APIHandle(self, sock)
        if self.api.client:
            self.api.client.close()
        self.api.client = a

        # XXX/bowei -- resend all of the queued SMS messages
        return a

#------------------------------------------------------------------------------
class APIHandle(io.ioloop.SockHandle):
    def __init__(self, api, sock):
        io.ioloop.SockHandle.__init__(self, sock)
        self.api = api

    def __repr__(self):
        return '<api.APIHandle %s>' % self.sock_

    def recv_frame(self, msg):
        self.api.process_api_msg(msg)

    def close(self):
        io.ioloop.SockHandle.close(self)
        self.api.client = None
        log.linfo('API socket closed')
